$(() => {
    const myAjax = (type, url, data, success) => {
        $.ajax({
            type,
            url: 'http://localhost:8080/api/v1' + url,
            headers: {
                Authorization: localStorage.getItem('dsj_token')
            },
            success,
        })
    }

    let data = {
        page:1,
        perpage: 10
    }

    const getList = () => {
        myAjax('GET', '/admin/article/query', data, (res) => {
            // console.log('1111', res);
            const htmlStr = template('monban', res)
            // console.log(htmlStr);
            $('tbody').html(htmlStr)
            //渲染分页器
            renderPager(res.data.totalCount)
        })
        // $.ajax({

        // type:'GET',
        // url:'http://localhost:8080/api/v1'+'/admin/article/query',
        // headers:{
        //     Authorization: localStorage.getItem('dsj_token')
        // },
        // data:{
        //     perpage: 10
        // },
        // success:(res) => {
        //     console.log(res);
        // }
        // })
    }
    getList()

    //搜索文章
    $('#btnSearch').on('click', () => {
        const keyword = $('#aname').val().trim()
        const categoryId = $('#selCategory').val()
        console.log(category);
        // data={key:keyword,perpage:10}
        data = { key: keyword, type: categoryId, perpage: 10 }
        getList()
    })

    const getCate = () => {
        myAjax('GET', '/admin/category/list', {}, (res) => {
            const htmlStr = template('category', res)
            $('#selCategory').html(htmlStr)
        })
    }
    getCate()

     // 业务5：获取文章类型id
     const categoryId = $('#selCategory').val()
     console.log('获取文章类型id', categoryId)
     // 业务6：获取文章状态
     const selStatus = $('#selStatus').val()
     console.log('获取文章状态', selStatus)
     // 修改请求参数
     
     data = { key: keyword, type: categoryId, state: selStatus, perpage: 10 }
     // 根据新请求参数，获取文章列表
     getList()

     $('tbody').on('click','delete',function(){
        layer.confirm('是否删除?', {icon: 3, title:'温馨提示'}, function(index){
            //do something
           const id= $(this).data('id')
            myAjax('GET','/admin/article/delete',{id},(res) => {
                getList()
            })
            layer.close(index);
          });
         
     })



    const renderPager=(count) => {
        layui.use('laypage', function(){
            var laypage = layui.laypage;
          
          //执行一个laypage实例
            laypage.render({
            elem: 'pager' //注意，这里的 pager 是 ID，不用加 # 号
            ,count: 70,
            curr:3,
            limit:20,   //页容量
            
            jump:function(obj,first){
                if(!first){
               // console.log('业务代码写这里');
                // 修改请求参数的页码为当前分页的页码
            data.page = obj.curr
            // 根据新页码获取列表
            getList()
                }
            }
          });
        });
       
    }
})